package mongoclient

import (
	"gopkg.in/mgo.v2/bson"
)

type Statement struct {
	cond  bson.M //条件语句
	limit int64
	skip  int64
	order interface{}
}

//or 操作里元素
type OrMember struct {
	Field    string
	Value    interface{}
	Operator string
}

func NewOrMember(filed string, value interface{}, operator ...string) *OrMember {
	var op string
	if len(operator) == 0 {
		op = "="
	} else {
		op = operator[0]
	}
	return &OrMember{
		Field:    filed,
		Value:    value,
		Operator: op,
	}
}

var operatorMap = map[string]string{
	"<":  "$lt",
	"<=": "$lte",
	">":  "$gt",
	">=": "$gte",
	"!=": "$ne",
}

//初始化构造
func NewStatement() *Statement {
	statement := &Statement{}
	statement.cond = make(bson.M)
	statement.Reset()
	return statement
}

//还原构造
func (s *Statement) Reset() {
	s.cond = bson.M{}
	s.limit = 0
	s.skip = 0
}
func (s *Statement) Where(filed string, value interface{}, operator ...string) *Statement {
	if len(operator) == 0 { //不带符号为 =
		s.cond[filed] = value
	} else {
		op := operator[0]
		if opm, ok := operatorMap[op]; ok == true {
			s.cond[filed] = bson.M{opm: value}
		} else {
			s.cond[filed] = value
		}
	}
	return s
}
func (s *Statement) OrWhere(members ...OrMember) *Statement {
	var childCond bson.M
	for _, member := range members {
		if opm, ok := operatorMap[member.Operator]; ok == true {
			childCond[member.Field] = bson.M{opm: member.Value}
		} else {
			childCond[member.Field] = member.Value
		}
	}
	s.cond["$or"] = childCond
	return s
}
func (s *Statement) WhereIn(field string, data []interface{}) *Statement {
	s.cond["$in"] = data
	return s
}

func (s *Statement) Skip(num int64) *Statement {
	s.skip = num
	return s
}
func (s *Statement) Limit(num int64) *Statement {
	s.limit = num
	return s
}
func (s *Statement) Order(order interface{}) *Statement {
	s.order = order
	return s
}
